import 'dart:async';
import 'dart:math';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'logic.dart';

class ChatVideoPlayerPage extends GetView<ChatVideoPlayerLogic> {
  const ChatVideoPlayerPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: 'F5F5F5'.stringToColor,
        body: Stack(
          children: [
            Container(
              color: Colors.black,
              alignment: Alignment.center,
              child: FijkView(
                player: controller.state.player,
                fit: FijkFit.cover,
                fsFit: FijkFit.fill,
                width: double.infinity,
                height: ScreenUtil().screenHeight,
                panelBuilder: (FijkPlayer player, FijkData data,
                    BuildContext context, Size viewSize, Rect texturePos) {
                  /// 使用自定义的布局
                  return CustomFijkWidgetBottom(
                    player: player,
                    buildContext: context,
                    viewSize: viewSize,
                    texturePos: texturePos,
                  );
                },
              ),
            ),
            Positioned(
                left: 0,
                right: 0,
                top: 0,
                height: ScreenUtil().statusBarHeight + 44.w,
                child: Container(
                  color: Colors.transparent,
                  padding: EdgeInsets.only(bottom: 12.w),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      SizedBox(width: 16.w),
                      InkWell(
                        onTap: () => Navigator.pop(context),
                        child: Icon(
                          Icons.arrow_back_ios,
                          weight: 12.w,
                          color: Colors.white,
                        ),
                      )
                    ],
                  ),
                ))
          ],
        ));
  }
}

class CustomFijkWidgetBottom extends StatefulWidget {
  final FijkPlayer player;
  final BuildContext buildContext;
  final Size viewSize;
  final Rect texturePos;

  const CustomFijkWidgetBottom({
    super.key,
    required this.player,
    required this.buildContext,
    required this.viewSize,
    required this.texturePos,
  });

  @override
  _CustomFijkWidgetBottomState createState() => _CustomFijkWidgetBottomState();
}

class _CustomFijkWidgetBottomState extends State<CustomFijkWidgetBottom> {
  FijkPlayer get player => widget.player;

  /// 播放状态
  bool _playing = false;

  /// 是否显示状态栏+菜单栏
  bool isPlayShowCont = true;

  /// 总时长
  String duration = "00:00:00";

  /// 已播放时长
  String durrentPos = "00:00:00";

  /// 进度条总长度
  double maxDurations = 0.0;

  /// 流监听器
  late StreamSubscription _currentPosSubs;


  /// 进度条当前进度
  double sliderValue = 0.0;

  @override
  void initState() {
    /// 提前加载
    /// 进行监听
    widget.player.addListener(_playerValueChanged);

    /// 接收流
    _currentPosSubs = widget.player.onCurrentPosUpdate.listen((v) {
      setState(() {
        /// 实时获取当前播放进度（进度条）
        sliderValue = v.inMilliseconds.toDouble();
        /// 实时获取当前播放进度（数字展示）
        durrentPos = v.toString().substring(0, v.toString().indexOf("."));
        if(durrentPos == duration){
          sliderValue = 0.0;
          widget.player.start();
        }
      });
    });

    /// 初始化
    super.initState();
  }

  /// 监听器
  void _playerValueChanged() {
    FijkValue value = player.value;

    /// 获取进度条总时长
    maxDurations = value.duration.inMilliseconds.toDouble();

    /// 获取展示的时长
    duration = value.duration
        .toString()
        .substring(0, value.duration.toString().indexOf("."));

    /// 播放状态
    bool playing = (value.state == FijkState.started);
    if (playing != _playing) setState(() => _playing = playing);
  }

  @override
  Widget build(BuildContext context) {
    Rect rect = Rect.fromLTRB(
      max(0.0, widget.texturePos.left),
      max(0.0, widget.texturePos.top),
      min(widget.viewSize.width, widget.texturePos.right),
      min(widget.viewSize.height, widget.texturePos.bottom),
    );

    return Positioned.fromRect(
      rect: rect,
      child: GestureDetector(
        onTap: () {
          setState(() {
            /// 显示 、隐藏  进度条+标题栏
            isPlayShowCont = !isPlayShowCont;
            /// 如果显示了  , 3秒后 隐藏进度条+标题栏
            if (isPlayShowCont) {
            }
          });
        },
        child: Stack(
          children: [
            Container(
                alignment: Alignment.bottomLeft,
                child: Container(
                  color: const Color.fromRGBO(0, 0, 0, 0.65),
                  height: 30.w,
                  padding: EdgeInsets.only(left: 12.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: SliderTheme(
                          data: SliderTheme.of(context).copyWith(
                            //已拖动的颜色
                            activeTrackColor: Colors.grey,
                            //未拖动的颜色
                            inactiveTrackColor: Colors.white,
                            //提示进度的气泡的背景色
                            valueIndicatorColor: Colors.red,
                            //提示进度的气泡文本的颜色
                            valueIndicatorTextStyle: const TextStyle(
                              color: Colors.white,
                            ),
                            //滑块中心的颜色
                            thumbColor: Colors.red,
                            //滑块边缘的颜色
                            overlayColor: Colors.transparent,
                            //对进度线分割后，断续线中间间隔的颜色
                            inactiveTickMarkColor: Colors.white,
                          ),
                          child: Slider(
                            value: sliderValue,
                            min: 0.0,
                            max: maxDurations,
                            divisions: 1000,
                            onChanged: (val) {
                              ///转化成double
                              setState(() =>
                              sliderValue = val.floorToDouble());
                              /// 设置进度
                              player.seekTo(sliderValue.toInt());
                            },
                          ),
                        ),
                      ),
                      Padding(padding: EdgeInsets.only(top: 6.w),child: Text(
                        "$durrentPos / $duration",
                        style: const TextStyle(color: Colors.white),
                      ),),
                      SizedBox(width: 12.w),
                    ],
                  ),
                )),
            Positioned(
                bottom: 17,
                left: 0,
                width: 30.w,
                height: 10.w,
                child: InkWell(
                    onTap: () => _playing
                        ? widget.player.pause()
                        : widget.player.start(),
                    child: Icon(
                      _playing ? Icons.pause : Icons.play_arrow,
                      color: Colors.white,
                    ))),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    /// 关闭监听
    player.removeListener(_playerValueChanged);
    /// 关闭流回调
    _currentPosSubs.cancel();
    super.dispose();
  }
}
